package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.admin.api.entity.SysDept;
import com.engine4cloud.tdf.admin.api.feign.RemoteDeptService;
import com.engine4cloud.tdf.common.core.constant.SecurityConstants;
import com.engine4cloud.tdf.common.core.constant.enums.DictNameEnum;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.core.util.R;
import com.engine4cloud.tdf.common.core.util.RetOps;
import com.engine4cloud.tdf.common.data.web.query.Pages;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.data.web.response.PageInfo;
import com.engine4cloud.tdf.common.data.web.response.Params;
import com.engine4cloud.tdf.common.security.service.TdfUser;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.GzryOtherConvert;
import com.engine4cloud.tdf.supervision.dto.IdentityUniqueCheckDTO;
import com.engine4cloud.tdf.supervision.dto.MobileUniqueCheckDTO;
import com.engine4cloud.tdf.supervision.dto.create.GzryOtherCreateDTO;
import com.engine4cloud.tdf.supervision.dto.query.GzryOtherQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.DictSelectResultDTO;
import com.engine4cloud.tdf.supervision.dto.result.GzryOtherResultDTO;
import com.engine4cloud.tdf.supervision.dto.update.GzryOtherUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.GzryOtherEntity;
import com.engine4cloud.tdf.supervision.mapper.GzryOtherMapper;
import com.engine4cloud.tdf.supervision.service.DictSelectService;
import com.engine4cloud.tdf.supervision.service.GzryOtherService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 其他工作人员
 *
 * @author wenjie
 * @date 2024-05-21 15:12:24
 */
@Service
public class GzryOtherServiceImpl extends ServiceImpl<GzryOtherMapper, GzryOtherEntity> implements GzryOtherService {

    @Resource
    private RemoteDeptService remoteDeptService;

    @Resource
    private DictSelectService dictSelectService;

    @Override
    public PageInfo<GzryOtherResultDTO> pageList(Params pageable, GzryOtherQueryDTO dto) {
        R<List<Long>> deptIdRemoteList = remoteDeptService.getDescendantIdList(dto.getDeptId(), SecurityConstants.FROM_IN);

        List<Long> deptIdList = RetOps.of(deptIdRemoteList).getData().filter(CollectionUtils::isNotEmpty)
                .orElseThrow(() -> new ValidateCodeException("没有数据权限!"));

        IPage<GzryOtherResultDTO> page = this.baseMapper.pageList(Pages.page(pageable), dto, deptIdList);
        return Pages.convert(page);
    }

    @Override
    public GzryOtherResultDTO getById(Long id) {
        //设置职业
        List<DictSelectResultDTO> positionList = dictSelectService.items(DictNameEnum.JOB.getType());
        return GzryOtherConvert.INSTANCE.convert(super.getById(id), positionList);
    }

    @Override
    public Boolean create(GzryOtherCreateDTO dto) {
        Boolean mobileUnique = this.checkUniqueByMobile(new MobileUniqueCheckDTO(dto.getSj()));
        if (!mobileUnique) {
            throw new ValidateCodeException("手机号已存在");
        }

        Boolean identityUnique = this.checkUniqueByIdentity(new IdentityUniqueCheckDTO(dto.getSfzh()));
        if (!identityUnique) {
            throw new ValidateCodeException("身份证号已存在");
        }

        TdfUser user = SecurityUtils.getUser();
        //设置所属部门
        SysDept dept = RetOps.of(remoteDeptService.detail(user.getDeptId(), SecurityConstants.FROM_IN)).getData()
                .orElseThrow(() -> new ValidateCodeException("没有数据权限!"));
        return super.save(GzryOtherConvert.INSTANCE.create(dto, dept, user.getTenantId()));
    }

    @Override
    public Boolean update(GzryOtherUpdateDTO dto) {
        GzryOtherEntity old = Optional.ofNullable(this.baseMapper.selectById(dto.getId()))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        Boolean mobileUnique = this.checkUniqueByMobile(new MobileUniqueCheckDTO(old.getId(), dto.getSj()));
        if (!mobileUnique) {
            throw new ValidateCodeException("手机号已存在");
        }

        Boolean identityUnique = this.checkUniqueByIdentity(new IdentityUniqueCheckDTO(old.getId(), dto.getSfzh()));
        if (!identityUnique) {
            throw new ValidateCodeException("证件号已存在");
        }

        return updateById(GzryOtherConvert.INSTANCE.update(dto));
    }

    @Override
    public Boolean checkUniqueByIdentity(IdentityUniqueCheckDTO dto) {
        GzryOtherQueryDTO query = new GzryOtherQueryDTO();
        query.setSfzh(dto.getIdentity());
        Optional<GzryOtherEntity> optional = Optional.ofNullable(getOne(wrapper(query)));
        return optional.map(dx -> Objects.equals(dx.getId(), dto.getId())).orElse(true);
    }

    @Override
    public Boolean checkUniqueByMobile(MobileUniqueCheckDTO dto) {
        GzryOtherQueryDTO query = new GzryOtherQueryDTO();
        query.setSj(dto.getMobile());
        Optional<GzryOtherEntity> optional = Optional.ofNullable(getOne(wrapper(query)));
        return optional.map(dx -> Objects.equals(dx.getId(), dto.getId())).orElse(true);
    }

    private LambdaQueryWrapper<GzryOtherEntity> wrapper(GzryOtherQueryDTO query) {
        LambdaQueryWrapper<GzryOtherEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(GzryOtherEntity::getId, v));
        Queries.accept(query.getSj(), v -> wrapper.eq(GzryOtherEntity::getSj, v));
        Queries.accept(query.getRybm(), v -> wrapper.eq(GzryOtherEntity::getRybm, v));
        Queries.accept(query.getSfzh(), v -> wrapper.eq(GzryOtherEntity::getSfzh, v));
        return wrapper;
    }
}